package br.com.jr2tecnologia.controller;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.MessageSenderLocal;
import br.com.jr2tecnologia.mail.Mailbox;
import br.com.jr2tecnologia.mail.SMSMail;
import br.com.jr2tecnologia.model.ConfigPersistenceLocal;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class ThreadMailboxMBean implements Serializable{
    
    private static final Logger logger = LoggerFactory.getLogger();
    
    @EJB
    private MessageSenderLocal messageSenderLocal;
    @EJB
    private ConfigPersistenceLocal configPersistence;

    private boolean flag = false;
    private ThreadMailbox threadMailbox = new ThreadMailbox();

    public void startListenerMailbox(){
        if(flag == false && !threadMailbox.isAlive()){
            logger.info("start listener mail box");
            flag = true;
            threadMailbox = new ThreadMailbox();
            threadMailbox.start();
        }else
            logger.info("cannot start thread. flag:<"+flag+"> thread is alive:<"+threadMailbox.isAlive()+">");
    }

    public void stopListenerMailbox(){
        flag = false;
    }

    private class ThreadMailbox extends Thread {
        public void run() {
            int timeSleepMailBox = Integer.parseInt(configPersistence.findConfigByName("time_sleep_mail_box").getValue());
            while (flag) {
                try {
                    try{
                        List<SMSMail> list = Mailbox.read();
                        for (SMSMail smsMail : list)
                            messageSenderLocal.persist(smsMail.getFrom(), smsMail.getPhone(), smsMail.getMessage());
                    }catch(RuntimeException ex){
                        logger.log(Level.SEVERE, "Cannot read mail box. This thread will go sleep 10 min and retry again", ex);
                        Thread.sleep(1000 * 60 * 10);//10 minutos
                    }

                    Thread.sleep(1000 * timeSleepMailBox);
                } catch (InterruptedException ex) {
                    logger.log(Level.SEVERE, "cannot put thread reading mail box to sleep", ex);
                }
            }
            logger.info("stop listener mail box");
        }
    }
}